package com.alex.webnote.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alex.common.ILogger;
import com.alex.common.cache.CacheKeys;
import com.alex.common.cache.CommonCacheManager;
import com.alex.webnote.dao.WebNoteDao;
import com.alex.webnote.domain.WebNotePO;
import com.alex.webnote.domain.WebNoteSummary;

@Controller
@RequestMapping("/webnotesummary")
public class SummaryController {

	private static final int SUMMARY_SHOW_SIZE = 10;

	@Autowired
	private WebNoteDao webNoteDao;

	@RequestMapping(method = { RequestMethod.GET })
	public String index(Model model) {

		List<WebNoteSummary> rt = CommonCacheManager.getInstance().get(
				CacheKeys.WebNoteSummaryList, "_");

		if (rt == null || rt.size() == 0) {
			List<WebNotePO> hotsList = webNoteDao
					.querySummaryByHots(SUMMARY_SHOW_SIZE);
			if (hotsList != null && hotsList.size() > 0) {
				int loops = hotsList.size() > SUMMARY_SHOW_SIZE ? SUMMARY_SHOW_SIZE
						: hotsList.size();
				rt = new ArrayList<WebNoteSummary>(loops);
				Set<Long> idSet = new HashSet<Long>(loops);
				List<WebNotePO> updatetimeList = webNoteDao
						.querySummaryByUpdatetime(SUMMARY_SHOW_SIZE);
				for (int i = 0; i < loops; i++) {
					WebNotePO poHots = hotsList.get(i);
					if (!idSet.contains(poHots.getId())) {
						rt.add(poHots.toSummary());
						idSet.add(poHots.getId());
						// check
						if (idSet.size() > SUMMARY_SHOW_SIZE) {
							break;
						}
					}

					WebNotePO poUpdatetime = updatetimeList.get(i);
					if (!idSet.contains(poUpdatetime.getId())) {
						rt.add(poUpdatetime.toSummary());
						idSet.add(poUpdatetime.getId());
						// check
						if (idSet.size() > SUMMARY_SHOW_SIZE) {
							break;
						}
					}
				}
				CommonCacheManager.getInstance().put(
						CacheKeys.WebNoteSummaryList, "_", rt);
			}
		} else {
			ILogger.logger_common
					.debug("Cache hit CacheKeys.WebNoteSummaryList.");
		}

		model.addAttribute("summary", rt);
		return "webnote/summary";
	}
}
